package com.bjtu.common.interceptor;

import com.bjtu.common.auth.AuthRedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        logger.info("Incoming request URI: " + uri);

        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            logger.warn("Token is missing for request URI: " + uri);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token is missing");
            return false;
        }

        // 验证 token 是否存在
        ValueOperations<Object, Object> ops = redisTemplate.opsForValue();
        Integer userId = (Integer) ops.get(AuthRedisKey.TOKEN_TO_UID + token);

        if (userId == null) {
            logger.warn("Invalid token for request URI: " + uri);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return false;
        }

        // 将 userId 存储在请求属性中，供后续使用
        request.setAttribute("userId", userId);
        logger.info("Token validated successfully for user ID: " + userId);
        return true;
    }
}

